package com.iot08.push.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import mob.push.api.config.MobPushConfig;
import mob.push.api.exception.ApiException;
import mob.push.api.http.Result;
import mob.push.api.res.PushV3Res;
import mob.push.api.utils.MD5;
import mob.push.api.utils.MobHelper;
import mob.push.api.utils.SafeUtil;
import okhttp3.*;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import org.springframework.http.converter.StringHttpMessageConverter;
import org.springframework.web.client.RestTemplate;
import mob.push.api.http.Http;

import java.io.IOException;
import java.lang.reflect.Type;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

/**
 * @author cwj
 * @description
 * @date 2024/11/18 15:57
 **/
public class TestDemo {

    private static final OkHttpClient CLIENT;
    private static final String WEB_ERROR;

    static {
        CLIENT = (new OkHttpClient.Builder()).connectTimeout(10L, TimeUnit.SECONDS).writeTimeout(10L, TimeUnit.SECONDS).readTimeout(10L, TimeUnit.SECONDS).connectionPool(new ConnectionPool(32, 5L, TimeUnit.SECONDS)).build();
        Result<?> webError = new Result();
        webError.setStatus(Result.ERROR);
        webError.setError("网络请求异常");
        WEB_ERROR = JSON.toJSONString(webError);
    }
    public static final MediaType JSON_MEDIA = MediaType.parse("application/json; charset=utf-8");

    public static JSONObject sendPost(String urlPath, Map<String, Object> paramMap, HttpHeaders headers,RestTemplate restTemplate){
        HttpEntity<Map<String, Object>> httpEntity = new HttpEntity<>(paramMap,headers);
        ResponseEntity<JSONObject> response = restTemplate.postForEntity(urlPath, httpEntity, JSONObject.class);
        return response.getBody();
    }

    public static <T> Result<T> post(String url, Map<String, String> headers, String data, Type cls,String appKey,String appSecret) throws ApiException {
        try {
            if (headers == null) {
                headers = new HashMap();
            }
            System.out.println("-------参数：---------"+data);
            ((Map)headers).put("sign", serverSign(data, appSecret));
            ((Map)headers).put("key", appKey);
            RequestBody body = RequestBody.create(JSON_MEDIA, data);
            Request request = (new Request.Builder()).url(url).headers(Headers.of((Map)headers)).post(body).build();
            return callAndGet(CLIENT.newCall(request), cls, data);
        } catch (Exception var6) {
            throw new ApiException(var6);
        }
    }


    private static <T> Result<T> callAndGet(Call call, final Type cls, final String data) {
        final CountDownLatch latch = new CountDownLatch(1);
        final Result<T> result = new Result();
        call.enqueue(new Callback() {
            public void onFailure(Call call, IOException e) {
                try {
                    result.setStatus(Result.ERROR);
                    result.setError("网络请求错误: " + e.getMessage());
                    latch.countDown();
                } finally {
                    latch.countDown();
                }

            }

            public void onResponse(Call call, Response response) {
                try {
                    result.setResponseCode(response.code());
                    String res = (String) SafeUtil.nullExecRes(response.body(), ResponseBody::string, WEB_ERROR);
                    //Http.log.info("MobRequest response: {}, request: {}", res, data);
                    JSONObject obj = JSON.parseObject(res);
                    Integer status = obj.getInteger("status");
                    if (Result.SUCCESS.equals(status)) {
                        String dataStr = obj.getString("res");
                        T datax = JSON.parseObject(dataStr, cls, new Feature[0]);
                        result.setRes(datax);
                    } else {
                        result.setStatus(status);
                        result.setError(obj.getString("error"));
                    }
                } catch (Exception var11) {
                    result.setStatus(Result.ERROR);
                    throw var11;
                } finally {
                    latch.countDown();
                }

            }
        });
        SafeUtil.safeExec(latch::await);
        return result;
    }

    public static String serverSign(String decodeData, String appSecret) {
        return MD5.hash(decodeData + appSecret, MobHelper.CHARSET_UTF8);
    }

    public static void  main(String args[]){
        String url = "http://api.push.mob.com/v3/push/createPush";

        String dataStr = "{\n" +
                "    \"appkey\":\"3a4e0ed9b5154\",\n" +
                "    \"pushFactoryExtra\":{\n" +
                "        \"huaweiExtra\":{\n" +
                "            \"category\":\"VOIP\",\n" +
                "            \"importance\":\"NORMAL\"\n" +
                "        },\n" +
                "        \"vivoExtra\":{\n" +
                "            \"category\":\"IM\",\n" +
                "            \"classification\":1\n" +
                "        }\n" +
                "    },\n" +
                "    \"pushForward\":{\n" +
                "        \"nextType\":2,\n" +
                "        \"scheme\":\"palmhang://palmhang/transfer_page\",\n" +
                "        \"schemeDataList\":[\n" +
                "            {\n" +
                "                \"key\":\"data\",\n" +
                "                \"value\":\"{\\\"type\\\":\\\"accountMessage\\\",\\\"message\\\":{\\\"openid\\\":\\\"402881e6929317b901929317b9910000\\\",\\\"type\\\":\\\"video\\\",\\\"video_type\\\":4,\\\"connection_address\\\":\\\"http:cn.router.justalkcloud.com:8080\\\",\\\"imei\\\":\\\"864721062271370\\\",\\\"call_type\\\":0}}\"\n" +
                "            }\n" +
                "        ]\n" +
                "    },\n" +
                "    \"pushNotify\":{\n" +
                "        \"content\":\"A9-小锄头邀请您视频通话\",\n" +
                "        \"extrasMapList\":[\n" +
                "\n" +
                "        ],\n" +
                "        \"iosProduction\":1,\n" +
                "        \"offlineSeconds\":3600,\n" +
                "        \"plats\":[\n" +
                "            1\n" +
                "        ],\n" +
                "        \"speed\":0,\n" +
                "        \"taskCron\":0,\n" +
                "        \"type\":1\n" +
                "    },\n" +
                "    \"pushOperator\":{\n" +
                "\n" +
                "    },\n" +
                "    \"pushTarget\":{\n" +
                "        \"alias\":[\n" +
                "            \"402881e6929317b901929317b9910000\"\n" +
                "        ],\n" +
                "        \"tagsType\":1,\n" +
                "        \"target\":2\n" +
                "    },\n" +
                "    \"source\":\"webapi\"\n" +
                "}";
        JSON.toJSONString(dataStr);
        Result<TestDemo> result = post(url,null,dataStr,TestDemo.class,"3a4e0ed9b5154","28ca4b977e52c1600f398f4a0fd72e1a");
        System.out.println("执行结果： " + result);
    }

    public static Map<String, Object> toMap(JSONObject jsonObject) {
        Map<String, Object> map = new HashMap<>();
        // 遍历 JSONObject 的键
        for (String key : jsonObject.keySet()) {
            Object value = jsonObject.get(key);
            // 如果值是 JSONObject 的话，递归转换
            if (value instanceof JSONObject) {
                value = toMap((JSONObject) value);
            }
            map.put(key, value);
        }
        return map;
    }

}

